package com.bifrost.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 富基美团中间库配置
 * @author sophia
 * @date 2018/7/12
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="mtEntityManagerFactory",
        transactionManagerRef="transactionManagerQuaternary",
        basePackages= {"com.bifrost.mtRepository"})
public class MeituanRepositoryConfig {

    @Autowired
    private JpaProperties jpaProperties;
    @Autowired
    @Qualifier("mtDataSource")
    private DataSource mtDataSource;

    @Bean(name = "mtEntityManager")
    public EntityManager mtEntityManager(EntityManagerFactoryBuilder builder) {
        return mtEntityManagerFactory(builder).getObject().createEntityManager();
    }

    @Bean(name = "mtEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean mtEntityManagerFactory (EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(mtDataSource)
                .properties(getVendorProperties(mtDataSource))
                .packages("com.bifrost.mtentity")
                .persistenceUnit("mtPersistenceUnit")
                .build();
    }

    private Map<String, String> getVendorProperties(DataSource dataSource) {
        jpaProperties.setDatabase(Database.ORACLE);
        Map<String,String> map = new HashMap<>(2);
        map.put("hibernate.hbm2ddl.auto","none");
        map.put("hibernate.dialect","org.hibernate.dialect.Oracle10gDialect");
        jpaProperties.setProperties(map);
        return  jpaProperties.getHibernateProperties(dataSource);
    }

    @Bean(name = "transactionManagerQuaternary")
    PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(mtEntityManagerFactory(builder).getObject());
    }
}
